const queue = []
let isFlushing = false
let currentPromise = null

// nextTick是Vue Scheduler思想的直接体现
export function nextTick(fn) {
    const p = currentPromise || Promise.resolve()
    return fn ? p.then(fn) : p;
}

export function queueJob(job) {
    if (!queue.length || !queue.includes(job)) {
        queue.push(job)
        queueFlush()
    }
}

function queueFlush() {
    if (!isFlushing) {
        isFlushing = true
        currentPromise = Promise.resolve().then(flushJobs)
    }
}

function flushJobs() {
    try {
        for (let i = 0; i < queue.length; i++) {
            const job = queue[i]
            job()
        }
    }
    finally {
        isFlushing = false
        queue.length = 0
        currentPromise = null
    }
}